<template>
  <div class="wchat">
    <Header
      title="微信"
      btn_icon="plus"
    />
    <div class="container" >
        <UserCell v-for="chatItem in chatDataList" :key="chatItem._id" :user="chatItem.target" :count="chatItem.count" 
                @click="$router.push({path:'/chat',query:{user:JSON.stringify(chatItem.target)}})"></UserCell>
    </div>
  </div>
</template>
<script>
import Header from "./../components/Header";
import UserCell from "./../components/UserCell";
import WSocket from "./../socket";
export default {
  components: { Header, UserCell },
  data() {
    return {
      chatDataList: []
    };
  },
  computed: {
    user() {
      return this.$store.getters.user;
    }
  },
  mounted(){
      WSocket.init({user:this.user},message =>{
        //  接收服务器发送过来的消息
          console.log(message)
        this.setMsgCount(message)
      },error =>{
          console.log(error)
      })
  },
  methods:{
      setMsgCount(message){
        // 判断好友是否在主页列表里
        let chatUser = this.chatDataList.filter (chatItem =>{
            //如果相等就代表有内容了
            return chatItem.target._id == message.from
        });
        // 如果好友在当前主面就让count+1,并将消息保存在列表 中
        if(chatUser.length >0){
            chatUser[0].count++;
            chatUser[0].message.push({
                msg:message.msg,
                source:'other'
            })
            this.saveMsg(chatUser[0].target,chatUser[0].count,chatUser[0].message)
        }else{
            // 如果好友不在主页列表中;就要获取信息然后渲染过来并提醒
            this.getUserInfo(message);
        }
      },
      getUserInfo(message){
        //  根据ID查询用户信息
        this.$axios(`/api/users/${message.from}`).then(res=>{
            console.log(res.data)
            const msg = [];
            msg.push({
                msg:message.msg,
                source:'other'
            });
            // 将消息保存在聊天列表中 count为1
            this.chatDataList.push({
                target:res.data,
                count:1,
                message:msg
            })
            this.saveMsg(res.data,1,msg)
        })
      },
    //   保存方法把消息放入数据库
    saveMsg(targetUser,count,msg){
        const messageObj = {
            target:{
                avatar:targetUser.avatar,
                name:targetUser.name,
                _id:targetUser._id
            },
            count:count,
            message:msg,
            user_id:this.user.id
        }
         this.$axios.post('/api/profile/addmsg',messageObj).then(res=>{
             console.log(`数据保存成功`)
        })
    }

  },
  beforeRouteEnter(to, from, next) {
    // 在页面每次进入的时候都刷新一次聊天列表
    next(vm => {
      // 从计算属性中得到所有的聊天内容
      vm.$axios.get(`/api/profile/msg/${vm.user.id}`).then(res => {
        vm.chatDataList = res.data;
      });
    });
  }
};
</script>
<style scoped>
.wchat{
    width: 100%;
    height: 100%;
    overflow: hidden;
}
.container{
   width: 100%;
   height: calc(100% - 50px);
   margin-top: 50px;
   overflow: auto;
}
</style>


